<template>
    <div class="tags-view-container">
        <scroll-pane ref="scrollPane" class="tags-view-wrapper">
            <router-link to="/home" class="tags-view-item">首页</router-link>
            <router-link ref="tag" v-for="tag in Array.from(visitedViews)" :key="tag.path"
                :class="isActive(tag) ? 'active' : ''" :to="tag" class="tags-view-item" @click="openMenu(tag, $event)">
                {{ tag.title }}
                <span v-if="tag.path !== '/home'" @click.prevent.stop="closeSelectedTag(tag)">×</span>
            </router-link>
        </scroll-pane>
        <el-dropdown class="tags-dropdown">
            <span class="el-dropdown-link">
                <el-icon class="el-icon--right">
                    <arrow-down />
                </el-icon>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="closeOthersTags">关闭其他</el-dropdown-item>
                    <el-dropdown-item @click="closeAllTags">关闭所有</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useTagsViewStore } from '@/store/tagsView';
import { useRoute, useRouter } from 'vue-router';
import ScrollPane from './ScrollPane.vue';

const store = useTagsViewStore();
const route = useRoute();
const router = useRouter();

const visible = ref(false);
const top = ref(0);
const left = ref(0);
const selectedTag = ref({});
const visitedViews = computed(() => store.visitedViews);
const tags = ref([]);
const scrollPane = ref(null);

// 页面加载时添加视图标签  
onMounted(() => {
    addViewTags();
});

// 监听路由变化  
watch(route, () => {
    addViewTags();
    moveToCurrentTag();
});

// 处理打开标签  
const addViewTags = () => {
    const currentRoute = generateRoute();
    selectedTag.value = currentRoute;
    if (!currentRoute) return;
    if (currentRoute.path !== '/home') {
        store.addVisitedViews(currentRoute);
    }
};

// 生成当前路由  
const generateRoute = () => {
    return route.name ? route : false;
};

// 检查是否为活动路由  
const isActive = (tag) => {
    return tag.path === route.path;
};

// 移动到当前标签  
const moveToCurrentTag = () => {
    const tagsRefs = tags.value;
    nextTick(() => {
        for (const tag of tagsRefs) {
            if (tag.to.path === route.path) {
                scrollPane.value.moveToTarget(tag.$el);
                break;
            }
        }
    });
};

// 关闭选定标签  
// const closeSelectedTag = async (view) => {
//     if (view.path === route.path) {
//         let index;
//         for (let key in visitedViews.value) {
//             index = key;
//         }
//         if (index > 0) {
//             await router.push(visitedViews.value[index - 1]);
//         } else {
//             await router.push('/');
//         }
//     }
//     await store.delVisitedViews(view);
// };
const closeSelectedTag = async (view) => {
    const currentVisitedViews = visitedViews.value;
    const currentIndex = currentVisitedViews.findIndex(v => v.path === view.path);
    const lastIndex = currentVisitedViews.length - 1;

    if (view.path !== route.path) {
        await store.delVisitedViews(view);
        return;
    }

    // 删除当前tag
    await store.delVisitedViews(view);

    await nextTick();

    if (currentIndex < lastIndex) {
        const lastTag = currentVisitedViews[lastIndex - 1];
        if (lastTag) {
            await router.push(lastTag);
        }
    } else if (currentIndex === lastIndex && currentIndex > 0) {
        const prevTag = currentVisitedViews[currentIndex - 1];
        if (prevTag) {
            await router.push(prevTag);
        }
    } else {
        await router.push('/');
    }
};

// 关闭其他标签  
const closeOthersTags = async () => {
    await router.push(selectedTag.value);
    await store.delOthersViews(selectedTag.value);
    moveToCurrentTag()
};

// 关闭所有标签  
const closeAllTags = () => {
    const homeTag = visitedViews.value.find(tag => tag.path === '/home');
    const otherTags = visitedViews.value.filter(tag => tag.path !== '/home');
    otherTags.forEach(tag => store.delVisitedViews(tag));
    if (homeTag) {
        store.visitedViews = [homeTag];
    } else {
        store.visitedViews = [];
    }
    router.push('/');
};

// 打开右键菜单  
const openMenu = (tag, e) => {
    visible.value = true;
    selectedTag.value = tag;
    const offsetLeft = e.currentTarget.getBoundingClientRect().left;
    left.value = e.clientX - offsetLeft + 15;
    top.value = e.clientY;
};

// 关闭菜单  
const closeMenu = () => {
    visible.value = false;
};

// 监听菜单可见性以添加/移除事件监听器  
watch(visible, (value) => {
    if (value) {
        document.body.addEventListener('click', closeMenu);
    } else {
        document.body.removeEventListener('click', closeMenu);
    }
});  
</script>

<style lang="scss" scoped>
.tags-view-container {
    display: flex;
    border-bottom: 1px solid #d8dce5;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .12), 0 0 3px 0 rgba(0, 0, 0, .04);

    .tags-view-wrapper {
        background: #fff;
        height: 100%;
        display: flex;
        align-items: flex-end;

        .tags-view-item {
            display: inline-block;
            position: relative;
            min-width: 40px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #d8dce5;
            color: #495060;
            background: #fff;
            padding: 0 8px;
            font-size: 14px;
            margin-left: 5px;
            text-decoration: none;

            &:first-of-type {
                margin-left: 15px;
            }

            &.active {
                color: #000;
            }
        }
    }

    .contextmenu {
        margin: 0;
        background: #fff;
        z-index: 100;
        position: absolute;
        list-style-type: none;
        padding: 5px 0;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 400;
        color: #333;
        box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);

        li {
            margin: 0;
            padding: 7px 16px;
            cursor: pointer;

            &:hover {
                background: #eee;
            }
        }
    }
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.tags-dropdown {
    width: 40px;
    line-height: 44px;

    :focus-visible {
        outline: none;
    }
}
</style>